package zhuzx.generator;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import org.zhuzx.util.ExceptionUtil;
import org.zhuzx.util.JdbcUtil;
import org.zhuzx.util.LambdaConstants;
import org.zhuzx.util.MicroUtil;

import java.sql.Connection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhuzx 2022/5/13
 */
@Slf4j
public class MpCodeGenerator {

	public static void main(String[] args) {
		String tableName = "data_change_log";
//		String url = "jdbc:mysql://10.88.0.18:3306/userportaldb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull";
//		String user = "userportal", password = "userportal123";
		String url = "jdbc:mysql://10.88.0.18:3306/proddb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull";
		String user = "prod", password = "prod123";
		
		FastAutoGenerator.create(url, user, password)
		.globalConfig(builder -> {
			builder.author("zhuzx")
					.enableSwagger()
					.fileOverride()
					.outputDir("D:/gen")
//					.outputDir("C:\\GitCode\\UserPortalServ\\src\\main\\java")
//					.outputDir("C:\\GitCode\\ProdMgntServ\\src\\main\\java")
		;})
		.packageConfig(builder -> {
			builder.parent("com.dobest.prod.cfg").controller("web").entity("db").mapper("dao.mapper").xml("dao.mapper")
//			builder.parent("com.dobest.userservice").controller("web").entity("po").mapper("dao").xml("dao")
					.service("service").serviceImpl("service")
//					.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:/MpCodeGenerator"))
			;
		})
		.strategyConfig(builder -> builder.addInclude(tableName
				)
				.addTablePrefix("t_", "c_", "feishu_", "basic_db").addTableSuffix("_fs_temp")
				.controllerBuilder().enableRestStyle()
//					.serviceBuilder().formatServiceImplFileName("%sService")
				.serviceBuilder().formatServiceFileName("%sService")
				.entityBuilder()
				.enableLombok()
				.build())
		.injectionConfig(builder -> {
			Map<String, Object> data = new LinkedHashMap<>(FreemarkerUtil.constructAllUtil());
			Connection conn = JdbcUtil.getDbConn(url, user, password);
			List<DbColumnMetadata> columns = DatabaseMetadataUtil.getColumns(conn, tableName);
			JdbcUtil.close(conn);
			data.put("columns", columns);
//			printFieldNameAndComment(columns, false);
			data.put("columnsMap", columns.stream().collect(Collectors.toMap(
					item -> item.javaName, item -> item, LambdaConstants.neverHappenMerger(), LinkedHashMap::new)));
			data.put("isHaveUserField", columns.stream().anyMatch(item ->
					item.oriName.equals("create_user") || item.oriName.equals("update_user")));
			data.put("enumFieldConstants", columns.stream().filter(item -> {
				try {
					String javaType = item.javaType;
					if (!javaType.contains(".")) {
						javaType = "java.lang." + javaType;
					}
					return
//							(item.oriName.endsWith("status") || item.oriName.endsWith("type")) &&
							Number.class.isAssignableFrom(Class.forName(javaType));
				} catch (ClassNotFoundException e) {
					ExceptionUtil.neverHappen();
					return false;
				}
			}).map(item -> {
				String code = DatabaseMetadataUtil.generateEnumConstantsCode(item.javaName, item.remark, item.javaType);
				if (code != null) {//每一行前面都加一个tab
					code = "\t" + code.replaceAll("\n", "\n\t");
				}
				return code;
			}).filter(Objects::nonNull).collect(Collectors.toList()));
			builder.customMap(data).build();
		})
		//默认的是Velocity引擎模板
		.templateEngine(new FreemarkerTemplateEngine())
		.execute();
		log.info("{}的相关代码已生成", tableName);
	}

	static void printFieldNameAndComment(List<DbColumnMetadata> columns, boolean enFront) {
		String line = MicroUtil.createRepeatedCharSequence('-', 20);
		System.out.println(line);
		columns.forEach(column -> {
			String s = enFront ? (column.javaName + "：" + column.remark) : (column.remark + "：" + column.javaName);
			System.out.println(s);
		});
		System.out.println(line);
	}

}